Javascript - 迴圈var, let


Mar 18, 2024

*var:
0.1秒後出現66666,因為var提升到for上面,迴圈會在一瞬間完成,i最後變成6,5個setTimeout的間隙時間也是一瞬間,所以在0.1秒後幾乎同時出現。

for (var i = 1; i <= 5; i++) {
  setTimeout(()=> {
    console.log(i)
  }, 100)
}

*let:
12345,每個數字中間間隔0.1秒

for (let i = 1; i <= 5; i++) {
  setTimeout(()=> {
    console.log(i)
  }, 100)
}






你可能感興趣的文章

Show Me the DAG - An Introduction to Causal Graphs

Show Me the DAG - An Introduction to Causal Graphs

LeetCode JS 1. Two Sum

LeetCode JS 1. Two Sum

氣泡排序(Bubble Sort)、插入排序(Insertion Sort)、選擇排序(Selection Sort)

氣泡排序(Bubble Sort)、插入排序(Insertion Sort)、選擇排序(Selection Sort)






留言討論






2
2
2